package com.leyou.gateway.filters;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author 虎哥
 */
@Slf4j
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class AuthFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 过滤器的类型
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER - 1;
    }

    /**
     *
     * @return true：则只需run方法，false：不执行run方法
     */
    @Override
    public boolean shouldFilter() {
        // 获取Request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 获取请求路径
        String path = request.getRequestURI();
        // 判断路径，是否是需要放行的路径
        boolean isAllow = isAllowPath(path);
        // 如果需要放行，则应该返回false
        return !isAllow;
    }

    private boolean isAllowPath(String path) {
        // 获取所有应该放行的路径
        List<String> allowPaths = filterProp.getAllowPaths();
        // 判断当前路径，是否是要放行的路径
        for (String allowPath : allowPaths) {
            if(path.startsWith(allowPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        // 1.获取Request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        try {
            // 2.获取用户的登录凭证jwt
            String token = CookieUtils.getCookieValue(request, jwtProp.getUser().getCookieName());
            // 3.解析jwt，获取用户身份
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
            //  3.1.如果解析成功，继续向下，校验token黑名单
            Boolean hasKey = redisTemplate.hasKey(payload.getId());
            if (hasKey != null && hasKey) {
                // 黑名单中有，拦截
                throw new RuntimeException("token已经失效。");
            }
            // 4.根据身份，查询用户权限信息
            UserInfo userInfo = payload.getUserInfo();
            // 5.获取当前请求资源（微服务接口路径）
            String requestURI = request.getRequestURI();
            // TODO 6.判断是否有访问资源的权限
            log.info("用户{},角色{} 正在访问{}", userInfo.getUsername(), userInfo.getRole(), requestURI);
        } catch (RuntimeException e) {
            // 校验身份和权限失败，拦截请求
            log.error("用户身份校验失败，原因:{}", e.getMessage(), e);
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
        }
        return null;
    }
}
